﻿using Common.Infrastructure.Logs;
using Elasticsearch.Net;
using Log.Api.Extensions;
using Log.Api.IService;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Log.Api
{
    public class EsJob : BackgroundService
    {
        private readonly IOptions<EsConfig> config;

        public EsJob(IOptions<EsConfig> config)
        {
            this.config = config;
        }

        public ElasticClient GetClient(string index)
        {
            if (config == null || config.Value == null || config.Value.Urls == null || !config.Value.Urls.Any())
            {
                throw new Exception("urls can not be null");
            }

            var uris = config.Value.Urls.Select(p => new Uri(p)).ToArray();
            if (uris == null || uris.Length < 1)
            {
                throw new Exception("uris can not be null");
            }

            ConnectionSettings connectionSetting;
            if (uris.Length == 1)
            {
                var connectionPool = new SingleNodeConnectionPool(uris.FirstOrDefault());
                connectionSetting = new ConnectionSettings(connectionPool);
            }
            else
            {
                var connectionPool = new SniffingConnectionPool(uris);
                connectionSetting = new ConnectionSettings(connectionPool);
            }

            if (!string.IsNullOrWhiteSpace(index))
            {
                index = index.ToLower();
                connectionSetting.DefaultIndex(index);
            }

            ////connectionSetting.BasicAuthentication("", ""); //设置账号密码
            return new ElasticClient(connectionSetting);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    LogHanddler("minigroupsynclog");
                    LogHanddler("minigroupdownextlog");
                    LogHanddler("minigroupcaperrorlog");
                    LogHanddler("minigroupsyslog");
                    Thread.Sleep(30 * 60 * 1000);
                });
            }
        }

        private void LogHanddler(string index)
        {
            var client = GetClient(index);
            var response = client.DeleteByQuery<SyncLogModel>(s => s.Query(q =>
             q.DateRange(d => d.Field(f => f.CT).LessThan(DateTime.Now.AddMonths(-1)))));
        }
    }
}
